package com.example.springmvcdemo2;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            Arrays.stream(cookies).forEach(ck-> System.out.println(ck.getName()+":"+ck.getValue()));
        }
        return "获取cookie";
    }
    @RequestMapping("/getC2")
    public String getCookie(@CookieValue("bite")String bite){
      return "从Cookie中获取值,bite:"+bite;
    }
    //设置Session
    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request){
        //从cookie中拿到了sessionID，然后根据sessionID获取到了Session对象,如果没有获取到，会创建一个Session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return  "设置session成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request){
        //从cookie中拿到了sessionID，然后根据sessionID获取到了Session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return  "从session中获取name:"+name;
    }
}
